<?php

namespace App\Console\Commands;

use Doctrine\Common\Cache\Cache;
use Illuminate\Console\Command;

class BtcPriceCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'btc_pricr';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取比特币实时价格';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        if (\Cache::has('btc_price') && \Cache::get('btc_price')) {
            $btc_price = \Cache::get('btc_price');
        }else{
            #获取汇率
            if (\Cache::has('usd_h') && \Cache::get('usd_h')) {
                $usd_h = \Cache::get('usd_h');
            }else{
                $client = new \GuzzleHttp\Client();
                $res = $client->request('GET', 'http://op.juhe.cn/onebox/exchange/currency?key=eff4c07281688c01b8a6cc29896e579d&from=USD&to=CNY');
                $res = json_decode($res->getBody(),true);
                $usd_h = $res['result'][0]['result'];
                \Cache::put('usd_h', $usd_h,now()->addMinutes(60));
            }
            #获取比特币实时价格
            $url = 'https://www.bitstamp.net/api/v2/ticker/btcusd?time='.time();
            $client = new \GuzzleHttp\Client();
            $res = $client->request('GET', $url);
            $res = json_decode($res->getBody(),true);
            $btc_price = $res['last']*$usd_h;
            \Cache::put('btc_price', $btc_price-700,now()->addMinutes(60));
        }
        dd($btc_price);
    }
}
